package liangtWorkSpace.springTest.aopProxyTest.factory;

import liangtWorkSpace.springTest.aopProxyTest.aspect.MyAspect;
import liangtWorkSpace.springTest.aopProxyTest.dao.CustomerDao;
import liangtWorkSpace.springTest.aopProxyTest.impl.CustomerDaoImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author liangt
 * @ClassName: MyBeanFactory
 * @title: MyBeanFactory
 * @projectName liangtWorkSpace.springTest.aopTest.factory
 * @description: TODO
 * @date 2020/10/13 18:10
 */
public class MyBeanFactory {

    public static CustomerDao getBean(){
        //准备目标类
        final CustomerDao customerDao = new CustomerDaoImpl();

        //准备切点
        final MyAspect myAspect = new MyAspect();

        return (CustomerDao) Proxy.newProxyInstance(MyBeanFactory.class.getClassLoader(), new Class[]{CustomerDao.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                myAspect.myBefore();//前增强
                Object obj = method.invoke(customerDao,args);
                myAspect.myAfter();//后增强
                return obj;
            }
        });
    }
}
